package com.example.administrator.zhjt.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.widget.GridView;

import com.android.volley.VolleyError;
import com.example.administrator.zhjt.R;
import com.example.administrator.zhjt.adapter.EnvironmentAdapter;
import com.example.administrator.zhjt.bean.Road;
import com.example.administrator.zhjt.db.EnvironmentDB;
import com.example.administrator.zhjt.util.DataStack;
import com.example.administrator.zhjt.util.MyVolley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.administrator.zhjt.db.EnvironmentDB.ENVIRONMENT_TABLE;

/**
 * Created by Administrator on 2017/5/16 0016.
 */

public class EnvironmentActivity extends Activity {

    public static final long TIME=5000;
    public static final long FIVE_TIME=300000;
    public static final long ONE_TIME=60000;

    private EnvironmentAdapter environmentAdapter;
    private GridView gridView;
    private List<EnvironmentAdapter.Bean> list=new ArrayList<>();
    private EnvironmentDB environmentDB;
    private SQLiteDatabase sqLiteDatabase;

    private String[] title={"空气温度","空气湿度","光照","CO2","PM2.5","道路状况"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.environment_layout);
        MyVolley.init(this);
        initView();
        handler.post(postRunable);
        handler.post(dataRunable);
        environmentDB=new EnvironmentDB(this);
    }

    public void initView(){
        gridView= (GridView) findViewById(R.id.gridview);
        environmentAdapter=new EnvironmentAdapter(list,this);
        gridView.setAdapter(environmentAdapter);
        for (int i=0;i<title.length;i++) {
            EnvironmentAdapter.Bean bean = environmentAdapter.new Bean();
            bean.setTitle(title[i]);
            list.add(bean);
        }
    }

    public void postEnvironment(){
        String url="http://192.168.1.101:8080/transportservice/action/GetAllSense.do";
        Map map=new HashMap();
        map.put("UserName","admin");
        JSONObject jsonObject=new JSONObject(map);
        MyVolley.Post(url,jsonObject, new MyVolley.OnResultListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    list.get(0).setValue(result.getInt("temperature"));
                    list.get(1).setValue(result.getInt("humidity"));
                    list.get(2).setValue(result.getInt("LightIntensity"));
                    list.get(3).setValue(result.getInt("co2"));
                    list.get(4).setValue(result.getInt("pm2.5"));
                    environmentAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {
                System.out.println(error);
            }
        });
    }

    List<Road> roads = new ArrayList<>();
    private void postRoad(){
        MyVolley.getRoadStatus(1, "admin", new MyVolley.OnResultListener() {
            @Override
            public void done(JSONObject result) {
                try {
                    if(result.getString("RESULT").equals("S")){
                        Road road = new Road();
                        road.setRoadId(1);
                        roads.add(road);
                        road.setBalance(result.getInt("Balance"));
                        environmentAdapter.notifyDataSetChanged();
                    }else{
                        list.get(5).setValue(-1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError error) {
                System.out.println(error);
            }
        });

    }

    Handler handler=new Handler();
    Runnable postRunable=new Runnable() {
        @Override
        public void run() {
            postEnvironment();
            postRoad();
            handler.postDelayed(postRunable,TIME);
        }
    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(postRunable);
        handler.removeCallbacks(dataRunable);
        super.onDestroy();
    }

    Runnable dataRunable=new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(dataRunable,ONE_TIME);
            List<EnvironmentAdapter.Bean> beanList=new ArrayList<>();
            beanList.addAll(list);
            invokeStack(beanList);
        }
    };

    private void invokeStack(List<EnvironmentAdapter.Bean> beanList){
        DataStack dataStack=new DataStack();
        for (EnvironmentAdapter.Bean bean:beanList){
            dataStack.push(bean);
            if (dataStack.size()==DataStack.MAX_SIZE){
                int sum=0;
                while (dataStack.size()>0){
                    sum+=dataStack.pop().getValue();
                }
                bean.setValue(sum/DataStack.MAX_SIZE);
            }
        }
    }

    public void insert(List<EnvironmentAdapter.Bean> beanList){
        ContentValues contentValues=new ContentValues();
        sqLiteDatabase=environmentDB.getWritableDatabase();
        for (int i=0;i<title.length;i++){
            contentValues.put(EnvironmentDB.KEY_SET[i],beanList.get(i).getValue());
        }
        contentValues.put(EnvironmentDB.KEY_CREATEAT,System.currentTimeMillis());
        sqLiteDatabase.insert(ENVIRONMENT_TABLE,null,contentValues);
    }

}
